document.addEventListener('DOMContentLoaded', function() {
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    const chatMessages = document.getElementById('chat-messages');

    // 连接到 SocketIO 服务器
    const socket = io();  // 自动连接当前页面的主机

    // 发送消息
    function sendMessage() {
        const content = messageInput.value.trim();
        if (content) {
            // 通过 SocketIO 发送消息
            socket.emit('send_message', { content: content });
            messageInput.value = '';  // 清空输入框
        }
    }

    // 接收新消息
    socket.on('new_message', function(data) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message';
        messageDiv.innerHTML = `
            <span class="username">${data.username}</span>
            <span class="time">${data.timestamp}</span>
            <div>${data.content}</div>
        `;
        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;  // 滚动到底部
    });

    // 接收系统消息（用户加入/离开）
    socket.on('system_message', function(data) {
        const systemDiv = document.createElement('div');
        systemDiv.className = 'system-message';
        systemDiv.innerHTML = `
            <span class="time">${data.timestamp}</span>
            <div>${data.content}</div>
        `;
        chatMessages.appendChild(systemDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    });

    // 绑定事件
    sendButton.addEventListener('click', sendMessage);
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
});